package com.iteaj.iot.plc.omron;

import com.iteaj.iot.message.DefaultMessageHead;
import com.iteaj.iot.plc.PlcClientProtocol;
import com.iteaj.iot.plc.PlcProtocolType;
import com.iteaj.iot.utils.ByteUtil;

public class OmronMessageHeader extends DefaultMessageHead {

    /**
     * 信息控制字段，默认0x80
     */
    public byte ICF = (byte) 0x80;

    /**
     * 系统使用的内部信息
     */
    public byte RSV = 0x00;

    /**
     * 网络层信息，默认0x02，如果有八层消息，就设置为0x07
     */
    public byte GCT = 0x02;

    /**
     * PLC的网络号地址，默认0x00
     */
    public byte DNA = 0x00;

    /**
     * PLC的单元号地址，通常都为0
     */
    public byte DA2 = 0x00;

    /**
     * 上位机的网络号地址
     */
    public byte SNA = 0x00;
    /**
     * 上位机的单元号地址
     */
    public byte SA2 = 0x00;

    /**
     * 设备的标识号
     */
    public byte SID = 0x00;

    public OmronMessageHeader() {
        super(null, null, PlcProtocolType.Omron);
    }

    protected OmronMessageHeader(byte[] message) {
        super(message);
    }

    protected OmronMessageHeader(String messageId) {
        super(null, messageId, PlcProtocolType.Omron);
    }

    public OmronMessageHeader(String equipCode, String messageId) {
        super(equipCode, messageId, PlcProtocolType.Omron);
    }

    public OmronMessageHeader buildRequestHeader(byte SA1, byte DA1, int bodyLength) {
        byte[] length = ByteUtil.getBytesOfReverse(bodyLength + 18);
        byte[] message = new byte[] {
                0x46, 0x49, 0x4E, 0x53, // FINS
                0x00, 0x00, 0x00, 0x0C, // 后面的命令长度
                0x00, 0x00, 0x00, 0x02,
                0x00, 0x00, 0x00, 0x00,
                ICF, RSV, GCT, DNA, DA1,
                DA2, SNA, SA1, SA2, SID
        };

        this.setMessage(message);
        System.arraycopy(length, 0, message, 4, 4);
        return this;
    }

    /**
     * @see PlcClientProtocol#sendRequest() 使用channelId作为messageId
     * @param messageId
     */
    @Override
    public OmronMessageHeader setMessageId(String messageId) {
        return (OmronMessageHeader) super.setMessageId(messageId);
    }
}
